package cn.kzgg.ymcc.service.impl;

import cn.kzgg.ymcc.domain.Login;
import cn.kzgg.ymcc.mapper.LoginMapper;
import cn.kzgg.ymcc.result.JSONResult;
import cn.kzgg.ymcc.service.ILoginService;
import cn.kzgg.ymcc.util.AssertUtil;
import cn.kzgg.ymcc.util.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author kzgg
 * @since 2022-07-15
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    private final String TOKEN_URL = "http://localhost:10040/oauth/token?client_id=%s&client_secret=%s&grant_type=password&username=%s&redirect_uri=http://www.baidu.com&password=%s";

    /**
     * 登录
     *
     * @param login
     * @return
     */
    @Override
    public JSONResult common(Login login) {
        //1.参数判断jsr303
        //2.账号要存在
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", login.getUsername());
        Login loginTmp = selectOne(wrapper);
        AssertUtil.isNotNull(loginTmp, "账号不存在");
        //地址拼接，用密码获取token
        String client_id = null;
        String client_secret = null;
        if (login.getType() == 0) {
            //后台登陆
            client_id = "admin";
            client_secret = "123";
        } else {
            //服务端是前台
            client_id = "website";
            client_secret = "123";
        }
        String url = String.format(TOKEN_URL, client_id, client_secret, login.getUsername(), login.getPassword());
        //将url转为map对象
        String strUrl = HttpUtil.sendPost(url, null);
        Map<String, Object> resultMap = JSON.parseObject(strUrl, Map.class);
        //将值返回给前端
        if (resultMap.containsKey("error_description")) {//没有获取到token
            return JSONResult.error(resultMap.get("error_description").toString());
        }else {
            return JSONResult.success(resultMap);
        }
    }
}
